﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Bussiness;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using LeSoft.Application.Web.Areas.ResourceManage.Controllers;
using LeSoft.Application.Cache;

namespace LeSoft.Application.Web.Areas.FinancialManage.Controllers
{
    public class ReceivableFeeItemsController : MvcControllerBase
    {
        private PStructBLL pstructbll = new PStructBLL();
        private OrganizeCache organizeCache = new OrganizeCache();
        private PStructCache pstructCache = new PStructCache();
        private RelationPCBLL relationPCBll = new RelationPCBLL();
        private CustomerInfoBLL cinfoBll = new CustomerInfoBLL();
        private ReceivableFeeItemsBLL receivableFeeItemsBLL = new ReceivableFeeItemsBLL();
        //
        // GET: /FinancialManage/ReceivableFeeItems/
        #region 视图
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Form()
        {
            return View();
        }
        #endregion
        #region 获取数据
        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetForm, "应收", "GetTree")]
        public ActionResult GetTree(string id = "0", string OrganizeId = "", bool IsSubstep = false)
        {
            List<TreeEntity> treeList = new List<TreeEntity>();
            if (id == "0")
            {
                treeList.Add(new TreeEntity { id = "ALL", text = "所有收费对象", value = "ALL", parentId = "0", isexpand = true, complete = true, hasChildren = true });
                treeList.Add(new TreeEntity { id = "ALLPstructs", text = "房屋业户", value = "ALLPstructs", parentId = "ALL", isexpand = false, complete = true, hasChildren = true, Attribute = "type", AttributeValue = "ALL" });
                treeList.Add(new TreeEntity { id = "ALLelse", text = "其他客户", value = "ALLelse", parentId = "ALL", isexpand = false, complete = true, hasChildren = true, Attribute = "type", AttributeValue = "ALL" });
                var LeseClient = new VendorBLL().GetList();
                if (!OperatorProvider.Provider.Current().IsSystem)
                {
                    var organizeids = organizeCache.GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                    LeseClient = LeseClient.Where(t => t.OrganizeId == null || organizeids.Contains(t.OrganizeId)).ToList();
                }
                if (!string.IsNullOrEmpty(OrganizeId))
                {
                    var organizeids = organizeCache.GetSonOrganizeId(OrganizeId);
                    LeseClient = LeseClient.Where(t => t.OrganizeId == null || organizeids.Contains(t.OrganizeId)).ToList();
                }
                foreach (var item in LeseClient)
                {

                    TreeEntity tree = new TreeEntity();
                    tree.id = item.Id;
                    tree.text = item.FullName;
                    tree.value = item.Id;
                    tree.parentId = "ALLelse";
                    tree.isexpand = false;
                    tree.complete = true;
                    tree.hasChildren = false;
                    tree.Attribute = "type";
                    tree.AttributeValue = "Vendor";
                    treeList.Add(tree);
                }
            }
            var data = pstructCache.GetList().Where(t => t.Type <= 5).OrderBy(t => t.Type).OrderBy(t => t.Code).ToList();
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = organizeCache.GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                data = data.Where(t => t.OrganizeId != null && organizeids.Contains(t.OrganizeId)).ToList();
            }
            if (!string.IsNullOrEmpty(OrganizeId))
            {
                var organizeids = organizeCache.GetSonOrganizeId(OrganizeId);
                data = data.Where(t => t.OrganizeId != null && organizeids.Contains(t.OrganizeId)).ToList();
            }
            if (data != null)
            {
                var pstructdata = IsSubstep ? data.Where(t => t.ParentId == id) : data;
                foreach (PStructEntity item in pstructdata)
                {
                    TreeEntity tree = new TreeEntity();
                    bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                    #region treename
                    if (item.Type == 5)
                    {
                        var relationpc = relationPCBll.GetPStructIdByEntity(item.Id);
                        if (relationpc == null)
                        {
                            tree.text = item.Name;
                            item.ActiveMark = 0;
                        }
                        else
                        {
                            var model = cinfoBll.GetEntity(relationpc.CustomerId);
                            if (model == null)
                            {
                                tree.text = item.Name;
                                item.ActiveMark = 0;
                            }
                            else
                            {
                                tree.text = item.Name + "<" + model.Name + ">"; item.ActiveMark = 1;
                                tree.Attribute = "RelationPCId";
                                tree.AttributeValue = relationpc.Id;
                            }
                        }
                    }
                    else
                        tree.text = item.Name;
                    #endregion
                    tree.id = item.Id;
                    tree.value = item.Id;
                    var ParentId = IsSubstep && id != "0" ? "0" : !string.IsNullOrEmpty(item.ParentId) && item.ParentId != "0" ? item.ParentId : "ALLPstructs";
                    tree.parentId = ParentId;
                    switch (item.Type)
                    {
                        case 1: tree.img = "fa fa-university"; break;
                        case 2: tree.img = "fa fa-building-o"; break;
                        case 4: tree.img = "fa fa-server"; break;
                        case 5: tree.img = "fa fa-cube"; break;
                        default:
                            tree.img = "fa fa-th-list";
                            break;
                    }
                    if (item.ActiveMark == 1)
                        tree.imgstyle = "color:#2df12d";
                    tree.isexpand = false;
                    tree.complete = !IsSubstep;
                    tree.hasChildren = hasChildren;
                    tree.AttributeA = "PsType";
                    tree.AttributeValueA = item.Type.ToString();
                    tree.Attribute = "type";
                    tree.AttributeValue = "PStruct";
                    treeList.Add(tree);
                }
            }
            return Content(treeList.TreeToJson());
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetList, "应收", "GetPageList")]
        public ActionResult GetPageList(Pagination pagination, string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            if (!queryParam["PStructId"].IsEmpty())
            {
                queryParam["PStructId"] = pstructCache.GetSonStructId(queryParam["PStructId"].ToString());
            }
            if (!queryParam["OrganizeId"].IsEmpty())
            {
                queryParam["OrganizeId"] = organizeCache.GetSonOrganizeId(queryParam["OrganizeId"].ToString());
            }
            var Json = queryParam.ToString();
            var data = receivableFeeItemsBLL.GetPageList(pagination, Json);

            foreach (var item in data)
            {
                item.ItemId = new FeeItemBLL().GetEntity("", item.ItemId).IsEmpty() ? "" : new FeeItemBLL().GetEntity("", item.ItemId).Name;
                var CustomerInfo = new CustomerInfoBLL().GetEntity(item.CustomerId);
                var vendor = new VendorBLL().GetEntity(item.CustomerId);
                item.CustomerId = CustomerInfo.IsEmpty() ? !vendor.IsEmpty() ? vendor.FullName : "" : CustomerInfo.Name;
                item.PStructId = new PStructBLL().GetEntity(item.PStructId).IsEmpty() ? "" : new PStructBLL().GetEntity(item.PStructId).Name;
            }
            if (!queryParam["CustomerName"].IsEmpty())
            {
                string CustomerName = queryParam["CustomerName"].ToString();
                data = data.Where(e => CustomerName.Contains(e.CustomerId));
            }
            var watch = CommonHelper.TimerStart();
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());

        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Ignore)]
        [HandlerAction(OperationType.GetForm, "应收", "GetFormJson")]
        public ActionResult GetFormJson(string keyValue)
        {
            var entity = receivableFeeItemsBLL.GetEntity(keyValue);
            var ItemName = new FeeItemBLL().GetEntity("", entity.ItemId).IsEmpty() ? "" : new FeeItemBLL().GetEntity("", entity.ItemId).Name;
            var CustomerName = new CustomerInfoBLL().GetEntity(entity.CustomerId).IsEmpty() ? "" : new CustomerInfoBLL().GetEntity(entity.CustomerId).Name;
            var PStructName = new PStructBLL().GetEntity(entity.PStructId).IsEmpty() ? "" : new PStructBLL().GetEntity(entity.PStructId).Name;
            var obj = new { entity = entity, ItemName = ItemName, CustomerName = CustomerName, PStructName = PStructName }.ToJson();
            return Content(obj);
        }
        #endregion

        #region 提交数据

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAuthorize(PermissionMode.Enforce)]
        public ActionResult RemoveForm(string keyValue)
        {
            receivableFeeItemsBLL.RemoveForm(keyValue);
            return Success("删除成功。");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Submit, "应收", "CheckAudit")]
        public ActionResult CheckAudit(string keyValue)
        {
            receivableFeeItemsBLL.CheckAudit(keyValue);
            return Success("审核成功。");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]
        [HandlerAction(OperationType.Create, "应收", "SaveForm")]
        public ActionResult SaveForm(string keyValue, ReceivableFeeItemsEntity entity)
        {
            receivableFeeItemsBLL.SaveForm(keyValue, entity);
            return Success("操作成功。");
        }
        #endregion
    }
}
